<script setup lang="ts">
import { ref, onMounted, reactive, computed, nextTick } from "vue";
import {
  ElMessage,
  ElMessageBox,
  ElButton,
  ElIcon,
  ElTag,
  ElInput
} from "element-plus";
import type { FormInstance, CheckboxValueType } from "element-plus";
import { PureTable } from "@pureadmin/table";
import {
  getRoleListByPage,
  getAllPermisson,
  getPermissionsBy,
  setRolePermission as apiSetRolePermission,
  addRole,
  deleteRole,
  setRoleNameAndDescription,
  setRoute,
  getRouterByPage,
  setRoleRouters,
  getPermissionsByPage,
  getAllTable,
  getAllTableField,
  getTableByPage,
  getTableFieldScopeAll,
  setTableFieldScope
} from "@/api/index";
import { Search, Refresh, InfoFilled, Plus } from "@element-plus/icons-vue";

// 角色数据接口
interface Role {
  id: number;
  name: string;
  description: string;
  created_at: string;
  updated_at: string;
  data_range?: number;
}

// 表信息接口
interface TableInfo {
  id: number;
  name: string;
  created_at: string;
  updated_at: string;
  description: string;
  permission_pid: number;
  permission_query_id: number;
}

// 表字段信息接口
interface TableField {
  field_id: number;
  table_id: number;
  table_name: string;
  field: string;
  type: string;
  view_permission: number;
  view_permission_name: string;
  set_permission: number;
  set_permission_name: string;
  created_at: string;
  updated_at: string;
  config: string;
  label: string;
}

// 权限数据接口
interface permission {
  role_id: number;
  admin_id: string;
  name: string;
  description: string;
}

// 权限数据接口
interface Permission {
  id: number;
  name: string;
  description: string;
  created_at: string;
  updated_at: string;
  pid: number;
  children?: Permission[];
}

// 修改路由相关的数据结构
interface RouteItem {
  id: number;
  role_ids: number[];
  component: {
    name: string | number;
  };
  meta?: {
    title?: string;
  };
  name?: string;
  path?: string;
}

const loading = ref(false);
const roleList = ref<Role[]>([]);
const dialogVisible = ref(false);
const permissionDialogVisible = ref(false);
const dialogType = ref<"add" | "edit">("add");
const formRef = ref<FormInstance>();

// 表单数据
const roleForm = ref<Role>({
  id: 0,
  name: "",
  description: "",
  created_at: "",
  updated_at: ""
});

// 权限数据
const permissionForm = ref<permission>({
  role_id: 0,
  admin_id: "",
  name: "",
  description: ""
});

// 权限相关数据
const permissionList = ref<Permission[]>([]);
const selectedPermissions = ref<Set<number>>(new Set());
const currentRole = ref<Role | null>(null);

// 表单验证规则
const rules = {
  name: [
    { required: true, message: "请输入角色名称", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
  ],
  description: [
    { required: true, message: "请输入角色描述", trigger: "blur" },
    { max: 200, message: "最大长度为 200 个字符", trigger: "blur" }
  ]
};

// 查询表单数据
const queryForm = reactive({
  page: 1,
  size: 10,
  name: "",
  description: "",
  admin_id: ""
});

// 获取角色列表
const fetchRoles = async () => {
  loading.value = true;
  try {
    const res = await getRoleListByPage(queryForm);
    if (res.status === "success") {
      roleList.value = res.data.records;
      // 更新分页信息
      pagination.total = res.data.pagination.total;
      pagination.currentPage = res.data.pagination.current_page;
      pagination.pageSize = res.data.pagination.per_page;
    } else {
      ElMessage.error(res.msg || "获取角色列表失败");
    }
  } catch (error: any) {
    console.error("获取角色列表失败:", error);
    ElMessage.error(error?.msg || "获取角色列表失败");
  } finally {
    loading.value = false;
  }
};

// 设置角色权限
const handleSetRolePermission = async (
  roleId: number,
  permissionIds: number[]
) => {
  try {
    const res = await apiSetRolePermission(roleId, permissionIds);
    if (res.status === "success") {
      ElMessage.success("设置权限成功");
      return true;
    }
    ElMessage.error(res.msg || "设置权限失败");
    return false;
  } catch (error: any) {
    ElMessage.error(error?.msg || "设置权限失败");
    return false;
  }
};

// 重置表单
const resetForm = () => {
  Object.keys(queryForm).forEach(key => {
    queryForm[key] = "";
  });
  queryForm.page = 1;
  queryForm.size = 10;
  fetchRoles();
};

// 查询方法
const handleQuery = () => {
  queryForm.page = 1;
  fetchRoles();
};

// 分页大小改变
const onSizeChange = (val: number) => {
  queryForm.size = val;
  fetchRoles();
};

// 当前页改变
const onCurrentChange = (val: number) => {
  queryForm.page = val;
  fetchRoles();
};

// 新增角色
const handleAdd = () => {
  dialogType.value = "add";
  roleForm.value = {
    id: 0,
    name: "",
    description: "",
    created_at: "",
    updated_at: ""
  };
  dialogVisible.value = true;
};

// 编辑角色
const handleEdit = (row: Role) => {
  dialogType.value = "edit";
  roleForm.value = { ...row };
  dialogVisible.value = true;
};

// 删除角色
const handleDelete = (row: Role) => {
  ElMessageBox.confirm(`确定要删除角色"${row.name}"吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        const res = await deleteRole(row.id);
        if (res.status === "success") {
          ElMessage.success("删除成功");
          fetchRoles(); // 重新加载列表
        } else {
          ElMessage.error(res.msg || "删除失败");
        }
      } catch (error: any) {
        ElMessage.error(error?.msg || "删除失败");
      }
    })
    .catch(() => {
      // 取消删除
    });
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async valid => {
    if (valid) {
      try {
        if (dialogType.value === "add") {
          const res = await addRole(
            roleForm.value.name,
            roleForm.value.description
          );
          if (res.status === "success") {
            ElMessage.success("新增角色成功");
            dialogVisible.value = false;
            fetchRoles(); // 重新加载列表
          } else {
            ElMessage.error(res.msg || "新增失败");
          }
        } else {
          // 调用编辑接口
          const res = await setRoleNameAndDescription(
            roleForm.value.id,
            roleForm.value.name,
            roleForm.value.description
          );
          if (res.status === "success") {
            ElMessage.success("编辑角色成功");
            dialogVisible.value = false;
            fetchRoles(); // 重新加载列表
          } else {
            ElMessage.error(res.msg || "编辑失败");
          }
        }
      } catch (error: any) {
        console.error("提交表单失败:", error);
        ElMessage.error(
          error?.msg || (dialogType.value === "add" ? "新增失败" : "编辑失败")
        );
      }
    }
  });
};

// 分页配置
const pagination = reactive({
  pageSize: 10,
  currentPage: 1,
  pageSizes: [10, 15, 20],
  total: 0,
  align: "right",
  background: true,
  size: "default"
});

// 定义表格列
const columns = [
  {
    label: "ID",
    prop: "id",
    sortable: true,
    align: "center",
    width: 90
  },
  {
    label: "角色名称",
    prop: "name",
    align: "center",
    minWidth: 150
  },
  {
    label: "描述",
    prop: "description",
    minWidth: 200,
    align: "center"
  },
  {
    label: "创建时间",
    prop: "created_at",
    width: 180,
    align: "center"
  },
  {
    label: "更新时间",
    prop: "updated_at",
    width: 180,
    align: "center"
  },
  {
    label: "操作",
    slot: "operation",
    width: 400,
    fixed: "right",
    align: "center"
  }
];

// 获取所有权限
const fetchAllPermissions = async () => {
  try {
    const res = await getAllPermisson();
    if (res.status === "success") {
      permissionList.value = res.data;
    }
  } catch (error) {
    console.error("获取权限列表失败:", error);
    ElMessage.error("获取权限列表失败");
  }
};

// 获取指定层级的权限
const getPermissionsByLevel = (
  rootPermission: Permission,
  targetLevel: number,
  parentPermission: Permission | null
): Permission[] => {
  // 第一层显示根权限
  if (targetLevel === 1) {
    return [rootPermission];
  }

  // 如果没有父级权限，返回空数组
  if (!parentPermission) {
    return [];
  }

  // 获取直接子权限
  return permissionList.value.filter(item => item.pid === parentPermission.id);
};

// 构建权限树数据
const buildPermissionTree = (permissions: Permission[]) => {
  // 创建一个映射表来存储每个权限的子权限
  const permissionMap = new Map<number, Permission[]>();

  // 初始化映射表
  permissions.forEach(permission => {
    if (!permissionMap.has(permission.pid)) {
      permissionMap.set(permission.pid, []);
    }
    permissionMap.get(permission.pid)?.push(permission);
  });

  // 递归构建树结构
  const buildTree = (pid: number): Permission[] => {
    const children = permissionMap.get(pid) || [];
    return children.map(child => ({
      ...child,
      children: buildTree(child.id)
    }));
  };

  // 从根节点开始构建树
  return buildTree(-1);
};

// 处理表格数据
const getTableData = () => {
  // 获取权限树
  const permissionTree = buildPermissionTree(permissionList.value);
  const tableData: any[] = [];

  // 递归处理权限树生成表格数据
  const processPermissionNode = (
    node: Permission,
    parentRow: any = null,
    level: number = 1
  ) => {
    // 创建当前行
    const currentRow = {
      id: node.id,
      permissions: [] as Permission[],
      [getColumnKey(level)]: node,
      spanInfo: {} as Record<string, number> // 添加跨行信息
    };

    // 如果有父行，继承父行的权限信息
    if (parentRow) {
      for (let i = 1; i < level; i++) {
        const key = getColumnKey(i);
        currentRow[key] = parentRow[key];
      }
    }

    // 添加当前行到表格数据
    tableData.push(currentRow);

    // 递归处理子节点
    if (node.children && node.children.length > 0) {
      node.children.forEach(child => {
        processPermissionNode(child, currentRow, level + 1);
      });
    }
  };

  // 处理每个根节点
  permissionTree.forEach(root => {
    processPermissionNode(root);
  });

  // 计算每列的合并信息
  const maxLevel = getMaxLevel();
  for (let level = 1; level <= maxLevel; level++) {
    const key = getColumnKey(level);
    let count = 0;
    let lastValue: any = null;

    tableData.forEach((row, index) => {
      if (lastValue && row[key]?.id === lastValue.id) {
        count++;
        row.spanInfo[key] = 0;
        tableData[index - count].spanInfo[key] = count + 1;
      } else {
        lastValue = row[key];
        count = 0;
        row.spanInfo[key] = 1;
      }
    });
  }

  return tableData;
};

// 处理单元格合并
const handleSpanMethod = ({ row, column, rowIndex, columnIndex }: any) => {
  if (column.property.startsWith("level")) {
    const spanCount = row.spanInfo[column.property];
    if (spanCount !== undefined) {
      return {
        rowspan: spanCount,
        colspan: 1
      };
    }
  }
  return {
    rowspan: 1,
    colspan: 1
  };
};

// 获取列名
const getColumnKey = (level: number): string => {
  return `level${level}`;
};

// 获取最大层级
const getMaxLevel = () => {
  let maxLevel = 1;

  const findMaxLevel = (node: Permission, level: number) => {
    maxLevel = Math.max(maxLevel, level);
    if (node.children && node.children.length > 0) {
      node.children.forEach(child => findMaxLevel(child, level + 1));
    }
  };

  const tree = buildPermissionTree(permissionList.value);
  tree.forEach(root => findMaxLevel(root, 1));

  return maxLevel;
};

// 修改编辑权限的方法
const handleEditPermissions = async (row: Role) => {
  try {
    currentRole.value = row;
    permissionDialogVisible.value = true;

    // 加载权限数据
    await fetchAllPermissions();
    await fetchPermissionTableData();

    // 获取当前角色的权限
    permissionForm.value.role_id = row.id;
    const res = await getPermissionsBy(permissionForm.value);
    if (res.status === "success") {
      selectedPermissions.value.clear();
      res.data.forEach((permission: Permission) => {
        selectedPermissions.value.add(permission.id);
        let currentPid = permission.pid;
        while (currentPid !== -1) {
          const parent = permissionList.value.find(p => p.id === currentPid);
          if (parent) {
            selectedPermissions.value.add(parent.id);
            currentPid = parent.pid;
          } else {
            break;
          }
        }
      });

      // 更新树形结构的选中状态
      nextTick(() => {
        updateTreeCheckedKeys();
      });
    }
  } catch (error) {
    console.error("获取角色权限失败:", error);
    ElMessage.error("获取角色权限失败");
    permissionDialogVisible.value = false;
  }
};

// 获取指定父ID的子权限
const getChildrenByPid = (pid: number): Permission[] => {
  return permissionList.value.filter(item => item.pid === pid);
};

// 处理权限选择变化
const handlePermissionChange = (
  permissionId: number,
  checked: CheckboxValueType
) => {
  const isChecked = Boolean(checked);
  if (isChecked) {
    selectedPermissions.value.add(permissionId);
    // 选中父节点时递归选中所有子节点
    const selectChildren = (pid: number) => {
      const children = permissionList.value.filter(p => p.pid === pid);
      children.forEach(child => {
        selectedPermissions.value.add(child.id);
        selectChildren(child.id);
      });
    };
    selectChildren(permissionId);
  } else {
    selectedPermissions.value.delete(permissionId);
    // 取消选中父节点时递归取消所有子节点
    const unselectChildren = (pid: number) => {
      const children = permissionList.value.filter(p => p.pid === pid);
      children.forEach(child => {
        selectedPermissions.value.delete(child.id);
        unselectChildren(child.id);
      });
    };
    unselectChildren(permissionId);
  }
};

// 检查权限是否被选中
const isPermissionSelected = (permissionId: number): boolean => {
  return selectedPermissions.value.has(permissionId);
};

// 处理树节点选中状态变化
const handleTreeCheck = (
  data: Permission,
  checked: { checkedKeys: number[]; checkedNodes: Permission[] }
) => {
  selectedPermissions.value = new Set(checked.checkedKeys);
};

// 提交权限设置
const handleSubmitPermissions = async () => {
  if (!currentRole.value) return;

  try {
    const success = await handleSetRolePermission(
      currentRole.value.id,
      Array.from(selectedPermissions.value)
    );
    if (success) {
      permissionDialogVisible.value = false;
    }
  } catch (error: any) {
    console.error("更新权限失败:", error);
    ElMessage.error(error?.msg || "更新权限失败");
  }
};

// 处理全选
const handleSelectAll = () => {
  // 递归选中所有权限
  const selectAll = (pid: number) => {
    const items = permissionList.value.filter(item => item.pid === pid);
    items.forEach(item => {
      selectedPermissions.value.add(item.id);
      selectAll(item.id);
    });
  };
  selectAll(-1);
};

// 处理取消全选
const handleUnselectAll = () => {
  selectedPermissions.value.clear();
};

// 在 data 部分修改和添加新的响应式变量
const routerDialogVisible = ref(false);
const currentRouteRole = ref<Role | null>(null);
const routerList = ref<RouteItem[]>([]);
const selectedRoutes = ref<number[]>([]);
const allSelectedRoutes = ref<Set<number>>(new Set());

// 路由查询表单
const routerQueryForm = reactive({
  page: 1,
  size: 10,
  role_id: 0
});

// 路由分页配置
const routerPagination = reactive({
  pageSize: 10,
  currentPage: 1,
  pageSizes: [10, 15, 20],
  total: 0,
  align: "right",
  background: true,
  size: "default"
});

// 修改获取路由列表的方法
const fetchRouterList = async () => {
  try {
    const res = await getRouterByPage({
      page: routerQueryForm.page,
      size: routerQueryForm.size
    });
    if (res.status === "success") {
      routerList.value = res.data.records;
      // 更新分页信息
      routerPagination.total = res.data.pagination.total;
      routerPagination.currentPage = res.data.pagination.current_page;
      routerPagination.pageSize = res.data.pagination.per_page;
    } else {
      ElMessage.error(res.msg || "获取路由列表失败");
    }
  } catch (error: any) {
    console.error("获取路由列表失败:", error);
    ElMessage.error(error?.msg || "获取路由列表失败");
  }
};

// 获取当前角色的路由列表
const fetchRoleRoutes = async (roleId: number) => {
  try {
    const res = await getRouterByPage({
      page: 1, // 获取第一页数据
      size: 100, // 获取所有数据
      role_id: roleId
    });
    if (res.status === "success") {
      // 清空之前的选择
      allSelectedRoutes.value.clear();
      // 设置已选中的路由到完整集合中
      res.data.records.forEach((route: any) => {
        allSelectedRoutes.value.add(route.id);
      });
      // 更新当前页面显示的选中状态
      updateCurrentPageSelection();
    } else {
      ElMessage.error(res.msg || "获取角色路由失败");
    }
  } catch (error: any) {
    console.error("获取角色路由失败:", error);
    ElMessage.error(error?.msg || "获取角色路由失败");
  }
};

// 添加更新当前页面选择的方法
const updateCurrentPageSelection = () => {
  selectedRoutes.value = routerList.value
    .filter(route => allSelectedRoutes.value.has(route.id))
    .map(route => route.id);
};

// 修改路由选择变化的处理方法
const handleRouterSelectionChange = (value: number[]) => {
  // 获取当前页面所有路由ID
  const currentPageRouteIds = routerList.value.map(route => route.id);

  // 从 allSelectedRoutes 中移除当前页面所有路由
  currentPageRouteIds.forEach(id => {
    allSelectedRoutes.value.delete(id);
  });

  // 添加新选中的路由到 allSelectedRoutes
  value.forEach(id => {
    allSelectedRoutes.value.add(id);
  });

  // 更新当前页面的选择
  selectedRoutes.value = value;
};

// 修改处理路由分页的方法
const handleRouterSizeChange = async (val: number) => {
  routerQueryForm.size = val;
  await fetchRouterList();
  updateCurrentPageSelection();
};

const handleRouterCurrentChange = async (val: number) => {
  routerQueryForm.page = val;
  await fetchRouterList();
  updateCurrentPageSelection();
};

// 修改全选和取消全选的方法
const handleRouterSelectAll = () => {
  routerList.value.forEach(route => {
    allSelectedRoutes.value.add(route.id);
  });
  updateCurrentPageSelection();
};

const handleRouterUnselectAll = () => {
  routerList.value.forEach(route => {
    allSelectedRoutes.value.delete(route.id);
  });
  updateCurrentPageSelection();
};

// 修改处理修改路由的方法
const handleEditRouter = async (row: Role) => {
  currentRouteRole.value = row;
  routerQueryForm.role_id = row.id;
  await fetchRouterList();
  await fetchRoleRoutes(row.id);
  routerDialogVisible.value = true;
};

// 修改提交路由修改的方法
const handleSubmitRouter = async () => {
  if (!currentRouteRole.value) return;

  try {
    // 发送修改请求，使用完整的选中集合
    const res = await setRoleRouters({
      role_id: currentRouteRole.value.id,
      route_ids: Array.from(allSelectedRoutes.value)
    });

    if (res.status === "success") {
      ElMessage.success("修改路由成功");
      routerDialogVisible.value = false;
    } else {
      ElMessage.error(res.msg || "修改路由失败");
    }
  } catch (error: any) {
    console.error("修改路由失败:", error);
    ElMessage.error(error?.msg || "修改路由失败");
  }
};

// 在 data 部分添加新的响应式变量
const activeTab = ref("tree");
const permissionTableData = ref<Permission[]>([]);
const permissionTableLoading = ref(false);
const permissionTablePagination = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
  pageSizes: [10, 20, 30, 50]
});

// 添加树形结构数据
const permissionTreeData = computed(() => {
  return buildPermissionTree(permissionList.value);
});

// 添加树节点选择处理方法
const handleTreeNodeCheck = (
  data: Permission,
  checked: { checkedKeys: number[]; halfCheckedKeys: number[] }
) => {
  selectedPermissions.value = new Set(checked.checkedKeys);
};

const treeRef = ref();

// 更新树形结构选中状态的方法
const updateTreeCheckedKeys = () => {
  if (treeRef.value) {
    treeRef.value.setCheckedKeys(Array.from(selectedPermissions.value));
  }
};

// 权限表格的查询表单
const permissionQueryForm = reactive({
  page: 1,
  size: 15,
  name: "",
  description: "",
  admin_id: "",
  role_id: ""
});

// 修改权限表格列定义
const permissionColumns = [
  {
    type: "selection",
    width: 55,
    align: "center",
    reserveSelection: true
  },
  {
    label: "ID",
    prop: "id",
    width: 80,
    align: "center"
  },
  {
    label: "权限名称",
    prop: "name",
    minWidth: 180,
    align: "center"
  },
  {
    label: "描述",
    prop: "description",
    minWidth: 200,
    align: "center"
  },
  {
    label: "上级ID",
    prop: "pid",
    width: 100,
    align: "center"
  },
  {
    label: "创建时间",
    prop: "created_at",
    width: 180,
    align: "center"
  },
  {
    label: "更新时间",
    prop: "updated_at",
    width: 180,
    align: "center"
  }
];

// 添加表格选择相关的方法
const permissionTableRef = ref();

// 处理表格选择变化
const handlePermissionTableSelect = (selection: Permission[]) => {
  // 更新选中的权限
  selectedPermissions.value.clear();
  selection.forEach(item => {
    selectedPermissions.value.add(item.id);
  });
};

// 处理表格全选
const handlePermissionTableSelectAll = (selection: Permission[]) => {
  // 更新选中的权限
  selectedPermissions.value.clear();
  selection.forEach(item => {
    selectedPermissions.value.add(item.id);
  });
};

// 修改获取权限表格数据的方法
const fetchPermissionTableData = async () => {
  permissionTableLoading.value = true;
  try {
    // 获取所有权限列表
    const res = await getPermissionsByPage({
      ...permissionQueryForm,
      // 移除 role_id，这样可以获取所有权限
      page: permissionQueryForm.page,
      size: permissionQueryForm.size
    });
    if (res.status === "success") {
      permissionTableData.value = res.data.records;
      permissionTablePagination.total = res.data.pagination.total;
      permissionTablePagination.currentPage = res.data.pagination.current_page;
      permissionTablePagination.pageSize = res.data.pagination.per_page;

      // 在数据加载完成后，设置选中状态
      nextTick(() => {
        if (permissionTableRef.value) {
          permissionTableData.value.forEach(row => {
            if (selectedPermissions.value.has(row.id)) {
              permissionTableRef.value.toggleRowSelection(row, true);
            }
          });
        }
      });
    } else {
      ElMessage.error(res.msg || "获取权限列表失败");
    }
  } catch (error: any) {
    console.error("获取权限列表失败:", error);
    ElMessage.error(error?.msg || "获取权限列表失败");
  } finally {
    permissionTableLoading.value = false;
  }
};

// 处理权限表格分页变化
const handlePermissionSizeChange = (val: number) => {
  permissionQueryForm.size = val;
  fetchPermissionTableData();
};

const handlePermissionCurrentChange = (val: number) => {
  permissionQueryForm.page = val;
  fetchPermissionTableData();
};

// 修改计算属性的实现
const groupedPermissions = computed(() => {
  const groups: Permission[][] = [];
  const itemsPerRow = 3; // 每行显示3个权限项
  const permissions = permissionTableData.value || [];

  for (let i = 0; i < permissions.length; i += itemsPerRow) {
    groups.push(permissions.slice(i, i + itemsPerRow));
  }

  return groups;
});

// 在 data 部分添加新的响应式变量
const dataRangeDialogVisible = ref(false);
const currentDataRangeRole = ref<Role | null>(null);
const tableList = ref<TableInfo[]>([]);
const currentTableFields = ref<TableField[]>([]);
const tableFieldsPagination = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
  pageSizes: [10, 20, 30, 50]
});

// 获取所有表信息
const fetchAllTables = async () => {
  try {
    const res = await getAllTable();
    if (res.status === "success") {
      tableList.value = res.data;
    } else {
      ElMessage.error(res.msg || "获取表信息失败");
    }
  } catch (error: any) {
    console.error("获取表信息失败:", error);
    ElMessage.error(error?.msg || "获取表信息失败");
  }
};

// 修改获取表字段信息的方法
const fetchTableFields = async (tableId: number) => {
  try {
    const res = await getTableByPage({
      table_id: tableId,
      page: tableFieldsPagination.currentPage,
      size: tableFieldsPagination.pageSize
    });
    if (res.status === "success") {
      currentTableFields.value = res.data.records;
      // 更新分页信息，使用 nextTick 确保状态更新
      nextTick(() => {
        tableFieldsPagination.total = res.data.pagination.total;
        tableFieldsPagination.currentPage = res.data.pagination.current_page;
        tableFieldsPagination.pageSize = res.data.pagination.per_page;
      });
    } else {
      ElMessage.error(res.msg || "获取表字段信息失败");
    }
  } catch (error: any) {
    console.error("获取表字段信息失败:", error);
    ElMessage.error(error?.msg || "获取表字段信息失败");
  }
};

// 处理数据范围的方法
const handleEditDataRange = async (row: Role) => {
  currentDataRangeRole.value = { ...row }; // 使用解构赋值创建新对象
  dataRangeDialogVisible.value = true;
  await fetchAllTables();
  if (row.data_range) {
    currentDataRangeRole.value.data_range = row.data_range;
    await fetchTableFields(row.data_range);
  } else if (tableList.value.length > 0) {
    // 如果没有默认选中的表，则选中第一个表
    currentDataRangeRole.value.data_range = tableList.value[0].id;
    await fetchTableFields(tableList.value[0].id);
  }
};

// 处理表切换
const handleTableChange = async (tableId: number) => {
  tableFieldsPagination.currentPage = 1;
  await fetchTableFields(tableId);
};

// 修改分页处理方法
const handleTableFieldsSizeChange = async (val: number) => {
  tableFieldsPagination.pageSize = val;
  tableFieldsPagination.currentPage = 1; // 切换每页条数时重置到第一页
  if (currentDataRangeRole.value?.data_range) {
    await fetchTableFields(currentDataRangeRole.value.data_range);
  }
};

const handleTableFieldsCurrentChange = async (val: number) => {
  tableFieldsPagination.currentPage = val;
  if (currentDataRangeRole.value?.data_range) {
    await fetchTableFields(currentDataRangeRole.value.data_range);
  }
};

// 在 data 部分添加新的响应式变量
const drawerVisible = ref(false);
const currentField = ref<TableField | null>(null);
const fieldScope = ref("");
const fieldScopeTags = ref<string[]>([]);
const inputVisible = ref(false);
const inputValue = ref("");
const InputRef = ref<InstanceType<typeof ElInput>>();

// 添加处理标签的方法
const handleClose = (tag: string) => {
  fieldScopeTags.value.splice(fieldScopeTags.value.indexOf(tag), 1);
  // 更新 fieldScope
  fieldScope.value = JSON.stringify(fieldScopeTags.value);
};

const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value?.input?.focus();
  });
};

const handleInputConfirm = () => {
  if (inputValue.value) {
    fieldScopeTags.value.push(inputValue.value);
    // 更新 fieldScope
    fieldScope.value = JSON.stringify(fieldScopeTags.value);
  }
  inputVisible.value = false;
  inputValue.value = "";
};

// 修改 handleEditFieldScope 方法
const handleEditFieldScope = async (row: TableField) => {
  currentField.value = row;
  fieldScope.value = ""; // 重置输入值
  fieldScopeTags.value = []; // 重置标签数组
  drawerVisible.value = true;

  try {
    const res = await getTableFieldScopeAll({
      role_id: currentDataRangeRole.value?.id,
      field_id: row.field_id,
      page: 1,
      size: 10
    });
    if (res.data.records[0]?.scope) {
      // 解析已有的范围数据
      try {
        const scopeArray = JSON.parse(res.data.records[0].scope);
        fieldScopeTags.value = scopeArray.map(String);
        fieldScope.value = JSON.stringify(scopeArray);
      } catch (e) {
        console.error("解析范围数据失败:", e);
      }
    }
  } catch (error) {
    console.error("获取字段范围失败:", error);
    ElMessage.error("获取字段范围失败");
  }
};

// 添加提交字段范围的方法
const handleSubmitFieldScope = async () => {
  if (!currentField.value || !currentDataRangeRole.value) return;

  try {
    // 当标签为空时传入["*"]
    const scopeValue =
      fieldScopeTags.value.length === 0
        ? JSON.stringify(["*"])
        : fieldScope.value;

    const res = await setTableFieldScope({
      role_id: currentDataRangeRole.value.id,
      field_id: currentField.value.field_id,
      scope: scopeValue
    });

    if (res.status === "success") {
      ElMessage.success("设置字段范围成功");
      drawerVisible.value = false;
      // 重新加载表字段数据
      if (currentDataRangeRole.value.data_range) {
        await fetchTableFields(currentDataRangeRole.value.data_range);
      }
    } else {
      ElMessage.error(res.msg || "设置字段范围失败");
    }
  } catch (error: any) {
    console.error("设置字段范围失败:", error);
    ElMessage.error(error?.msg || "设置字段范围失败");
  }
};

// 添加重置数据范围数据的方法
const resetDataRangeData = () => {
  if (currentDataRangeRole.value) {
    currentDataRangeRole.value.data_range = undefined;
  }
  currentDataRangeRole.value = null;
  tableList.value = [];
  currentTableFields.value = [];
  tableFieldsPagination.total = 0;
  tableFieldsPagination.currentPage = 1;
  tableFieldsPagination.pageSize = 10;
};

onMounted(() => {
  fetchRoles();
});
</script>

<template>
  <div class="role-container">
    <el-card v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>角色管理</span>
        </div>
      </template>

      <!-- 查询表单 -->
      <el-form :inline="true" :model="queryForm" class="mb-4">
        <el-form-item label="角色名称">
          <el-input
            v-model="queryForm.name"
            placeholder="请输入角色名称"
            clearable
            class="!w-[180px]"
          />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="queryForm.description"
            placeholder="请输入描述"
            clearable
            class="!w-[180px]"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon class="mr-2"><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetForm">
            <el-icon class="mr-2"><Refresh /></el-icon>重置
          </el-button>
          <el-button type="success" @click="handleAdd">
            <el-icon class="mr-2"><Plus /></el-icon>添加角色
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 角色列表 -->
      <PureTable
        row-key="id"
        :data="roleList"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        header-align="center"
        align="center"
        border
        @page-size-change="onSizeChange"
        @page-current-change="onCurrentChange"
      >
        <template #operation="{ row }">
          <el-tag
            class="mx-1 cursor-pointer"
            type="primary"
            effect="plain"
            @click="handleEdit(row)"
          >
            编辑信息
          </el-tag>
          <el-tag
            class="mx-1 cursor-pointer"
            type="success"
            effect="plain"
            @click="handleEditPermissions(row)"
          >
            编辑权限
          </el-tag>
          <el-tag
            class="mx-1 cursor-pointer"
            type="warning"
            effect="plain"
            @click="handleEditRouter(row)"
          >
            修改路由
          </el-tag>
          <el-tag
            class="mx-1 cursor-pointer"
            type="info"
            effect="plain"
            @click="handleEditDataRange(row)"
          >
            查看范围
          </el-tag>
          <el-tag
            class="mx-1 cursor-pointer"
            type="danger"
            effect="plain"
            @click="handleDelete(row)"
          >
            删除角色
          </el-tag>
        </template>
      </PureTable>
    </el-card>

    <!-- 新增/编辑角色对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增角色' : '编辑角色'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="roleForm"
        :rules="rules"
        label-width="80px"
        status-icon
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="20"
            placeholder="请输入角色描述"
            resize="none"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改权限编辑对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="编辑权限"
      width="90%"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <div class="permission-header mb-4">
        <span class="text-lg font-bold"
          >{{ currentRole?.name }} - 权限配置</span
        >
        <el-button-group>
          <el-button type="primary" @click="handleSelectAll">全选</el-button>
          <el-button type="info" @click="handleUnselectAll">取消全选</el-button>
        </el-button-group>
      </div>

      <el-tabs v-model="activeTab" class="permission-tabs">
        <el-tab-pane label="树形结构" name="tree">
          <div class="permission-tree-container">
            <el-table
              :data="getTableData()"
              style="width: 100%"
              row-key="id"
              border
              :span-method="handleSpanMethod"
            >
              <el-table-column
                v-for="level in getMaxLevel()"
                :key="level"
                :label="`${level}级权限`"
                :prop="getColumnKey(level)"
                min-width="200"
              >
                <template #default="{ row }">
                  <div v-if="row[`level${level}`]" class="permission-item">
                    <el-checkbox
                      :model-value="
                        isPermissionSelected(row[`level${level}`].id)
                      "
                      @change="
                        val =>
                          handlePermissionChange(row[`level${level}`].id, val)
                      "
                    >
                      {{
                        row[`level${level}`].description ||
                        row[`level${level}`].name
                      }}
                    </el-checkbox>
                    <el-tooltip effect="dark" placement="top">
                      <template #content>
                        <div>{{ row[`level${level}`].name }}</div>
                      </template>
                      <el-icon class="info-icon"><InfoFilled /></el-icon>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <el-tab-pane label="纵向树形" name="vertical-tree">
          <div class="vertical-tree-container">
            <el-tree
              ref="treeRef"
              :data="permissionTreeData"
              :props="{
                children: 'children',
                label: item => item.description || item.name
              }"
              show-checkbox
              node-key="id"
              :check-strictly="true"
              :default-checked-keys="Array.from(selectedPermissions)"
              @check="handleTreeNodeCheck"
            >
              <template #default="{ data }">
                <div class="custom-tree-node">
                  <span>{{ data.description || data.name }}</span>
                  <el-tooltip
                    effect="dark"
                    :content="'权限标识: ' + data.name"
                    placement="right"
                  >
                    <el-icon class="info-icon"><InfoFilled /></el-icon>
                  </el-tooltip>
                </div>
              </template>
            </el-tree>
          </div>
        </el-tab-pane>

        <el-tab-pane label="表格结构" name="table">
          <div class="permission-table-container">
            <!-- 搜索表单 -->
            <el-form :inline="true" :model="permissionQueryForm" class="mb-4">
              <el-form-item label="权限名称">
                <el-input
                  v-model="permissionQueryForm.name"
                  placeholder="请输入权限名称"
                  clearable
                  @keyup.enter="fetchPermissionTableData"
                />
              </el-form-item>
              <el-form-item label="描述">
                <el-input
                  v-model="permissionQueryForm.description"
                  placeholder="请输入描述"
                  clearable
                  @keyup.enter="fetchPermissionTableData"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="fetchPermissionTableData">
                  <el-icon class="mr-2"><Search /></el-icon>查询
                </el-button>
                <el-button
                  @click="
                    () => {
                      permissionQueryForm.name = '';
                      permissionQueryForm.description = '';
                      fetchPermissionTableData();
                    }
                  "
                >
                  <el-icon class="mr-2"><Refresh /></el-icon>重置
                </el-button>
              </el-form-item>
            </el-form>

            <!-- 矩阵布局的权限列表 -->
            <div v-loading="permissionTableLoading" class="permission-matrix">
              <template v-if="permissionTableData.length > 0">
                <div
                  v-for="(group, groupIndex) in groupedPermissions"
                  :key="groupIndex"
                  class="permission-row"
                >
                  <div
                    v-for="permission in group"
                    :key="permission.id"
                    class="permission-card"
                  >
                    <el-checkbox
                      :model-value="selectedPermissions.has(permission.id)"
                      @change="
                        val => handlePermissionChange(permission.id, val)
                      "
                    >
                      <div class="permission-card-content">
                        <div class="permission-title">
                          {{ permission.name }}
                          {{ permission.description || permission.name }}
                          <el-tooltip effect="dark" placement="top">
                            <template #content>
                              <div>权限标识：{{ permission.name }}</div>
                              <div>创建时间：{{ permission.created_at }}</div>
                              <div>更新时间：{{ permission.updated_at }}</div>
                            </template>
                            <el-icon class="info-icon"><InfoFilled /></el-icon>
                          </el-tooltip>
                        </div>
                        <div class="permission-info">
                          <span class="permission-id"
                            >ID: {{ permission.id }}</span
                          >
                          <span class="permission-pid"
                            >上级ID: {{ permission.pid }}</span
                          >
                        </div>
                      </div>
                    </el-checkbox>
                  </div>
                </div>
              </template>
              <el-empty v-else description="暂无数据" />
            </div>

            <!-- 分页器 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="permissionTablePagination.currentPage"
                v-model:page-size="permissionTablePagination.pageSize"
                :page-sizes="permissionTablePagination.pageSizes"
                :total="permissionTablePagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handlePermissionSizeChange"
                @current-change="handlePermissionCurrentChange"
              />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitPermissions"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 修改路由编辑对话框 -->
    <el-dialog
      v-model="routerDialogVisible"
      title="修改路由"
      width="1000px"
      :close-on-click-modal="false"
    >
      <div class="router-dialog-content">
        <div class="dialog-header">
          <span class="text-lg font-bold"
            >{{ currentRouteRole?.name }} - 路由配置</span
          >
          <el-button-group>
            <el-button type="primary" @click="handleRouterSelectAll"
              >全选</el-button
            >
            <el-button type="info" @click="handleRouterUnselectAll"
              >取消全选</el-button
            >
          </el-button-group>
        </div>
        <div class="router-list">
          <el-checkbox-group
            v-model="selectedRoutes"
            @change="handleRouterSelectionChange"
          >
            <div v-for="route in routerList" :key="route.id" class="route-item">
              <el-checkbox :label="route.id">
                <div class="route-info">
                  <span class="route-title">{{
                    route.meta?.title || route.name
                  }}</span>
                  <el-tooltip
                    v-if="route.path"
                    effect="dark"
                    :content="route.path"
                    placement="top"
                  >
                    <el-icon class="info-icon"><InfoFilled /></el-icon>
                  </el-tooltip>
                </div>
              </el-checkbox>
            </div>
          </el-checkbox-group>
        </div>
        <!-- 添加分页组件 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="routerPagination.currentPage"
            v-model:page-size="routerPagination.pageSize"
            :page-sizes="routerPagination.pageSizes"
            :background="routerPagination.background"
            :total="routerPagination.total"
            :layout="'total, sizes, prev, pager, next, jumper'"
            @size-change="handleRouterSizeChange"
            @current-change="handleRouterCurrentChange"
          />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="routerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitRouter">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 数据范围对话框 -->
    <el-dialog
      v-model="dataRangeDialogVisible"
      :title="`数据范围 - ${currentDataRangeRole?.name || ''}`"
      width="1200px"
      :close-on-click-modal="false"
      @closed="resetDataRangeData"
    >
      <div class="data-range-content">
        <div class="form-item">
          <label class="label">表信息</label>
          <el-select
            v-model="currentDataRangeRole.data_range"
            placeholder="请选择表信息"
            @change="handleTableChange"
          >
            <el-option
              v-for="table in tableList"
              :key="table.id"
              :label="table.description || table.name"
              :value="table.id"
            >
              <div
                style="
                  display: flex;
                  align-items: center;
                  justify-content: space-between;
                "
              >
                <span>{{ table.description || table.name }}</span>
                <span
                  style="font-size: 13px; color: var(--el-text-color-secondary)"
                  >{{ table.name }}</span
                >
              </div>
            </el-option>
          </el-select>
        </div>
        <!-- 表字段信息表格 -->
        <el-table
          :data="currentTableFields"
          style="width: 100%; margin-top: 20px"
          border
        >
          <el-table-column prop="field" label="字段名" width="120" />
          <el-table-column prop="label" label="字段标签" width="120" />
          <el-table-column prop="type" label="字段类型" width="100" />
          <el-table-column prop="view_permission_name" label="查看权限" />
          <el-table-column prop="set_permission_name" label="设置权限" />
          <el-table-column label="配置信息" min-width="100">
            <template #default="{ row }">
              <pre>{{ JSON.parse(row.config) }}</pre>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" width="160" />
          <el-table-column prop="updated_at" label="更新时间" width="160" />
          <!-- 添加操作列 -->
          <el-table-column label="操作" width="70" fixed="right">
            <template #default="{ row }">
              <el-tag
                type="warning"
                effect="plain"
                class="cursor-pointer"
                @click="handleEditFieldScope(row)"
              >
                修改范围
              </el-tag>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页器 -->
        <div class="pagination-container" style="margin-top: 20px">
          <el-pagination
            v-model:current-page="tableFieldsPagination.currentPage"
            v-model:page-size="tableFieldsPagination.pageSize"
            :page-sizes="tableFieldsPagination.pageSizes"
            :total="tableFieldsPagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleTableFieldsSizeChange"
            @current-change="handleTableFieldsCurrentChange"
          />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dataRangeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="dataRangeDialogVisible = false"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 添加字段范围编辑抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      title="修改字段范围"
      :size="400"
      :destroy-on-close="true"
    >
      <div class="drawer-content">
        <div class="field-info mb-4">
          <p><strong>字段名：</strong>{{ currentField?.field }}</p>
          <p><strong>字段标签：</strong>{{ currentField?.label }}</p>
        </div>

        <div class="tags-container">
          <el-tag
            v-for="tag in fieldScopeTags"
            :key="tag"
            class="mx-1"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="inputVisible"
            ref="InputRef"
            v-model="inputValue"
            class="ml-1 w-20"
            size="small"
            @keyup.enter="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button
            v-else
            class="button-new-tag ml-1"
            size="small"
            @click="showInput"
          >
            + 添加范围
          </el-button>
        </div>

        <div class="drawer-footer">
          <el-button @click="drawerVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitFieldScope">
            确定
          </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<style lang="scss" scoped>
.role-container {
  padding: 20px;

  .card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .permission-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 16px;
    margin-bottom: 16px;
  }

  .permission-tree-container {
    height: calc(90vh - 280px);
    overflow-y: auto;

    :deep(.el-table) {
      .el-table__row {
        background-color: var(--el-bg-color);
      }

      .el-table__cell {
        padding: 4px 0;
      }

      .cell {
        padding: 0 8px;
      }
    }
  }

  .permission-item {
    display: flex;
    align-items: center;
    min-height: 32px;
    padding: 4px;
    transition: all 0.2s;

    .el-checkbox {
      flex: 1;
      margin-right: 8px;

      :deep(.el-checkbox__label) {
        line-height: 1.4;
        word-break: break-all;
        white-space: normal;
      }
    }

    .info-icon {
      flex-shrink: 0;
      margin-left: 4px;
      font-size: 14px;
      color: var(--el-text-color-secondary);
      cursor: pointer;

      &:hover {
        color: var(--el-color-primary);
      }
    }

    &:hover {
      background-color: var(--el-fill-color-light);
      border-radius: 4px;
    }
  }

  :deep(.el-table) {
    // 表格基础样式
    .cell {
      padding: 8px 0;
      line-height: 1.5;
    }
    // 表头样式
    .el-table__header {
      th {
        height: 50px;
        font-weight: bold;
        color: var(--el-text-color-primary);
        background-color: var(--el-fill-color-light);
      }
    }
  }
}

:deep(.el-dialog) {
  .el-dialog__body {
    height: auto;
    max-height: none;
    padding: 30px 20px;
  }

  .el-textarea__inner {
    min-height: 120px !important;
  }
}

:deep(.el-tooltip__popper) {
  max-width: 300px;
  font-family: var(--el-font-family);

  .text-gray-400 {
    color: var(--el-text-color-secondary);
  }

  .mt-1 {
    margin-top: 4px;
  }
}

.mx-1 {
  margin: 0 4px;
}

.cursor-pointer {
  cursor: pointer;
}

.router-dialog-content {
  display: flex;
  flex-direction: column;
  height: 600px;
  padding: 0 20px;

  .dialog-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px 0;
    margin-bottom: 16px;

    .text-lg {
      font-size: 16px;
      color: var(--el-text-color-primary);
    }
  }

  .router-list {
    flex: 1;
    padding: 10px;
    overflow-y: auto;
    border-radius: 8px;
  }

  .route-item {
    padding: 12px 16px;
    margin: 8px 0;
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 6px;
    transition: all 0.3s ease;

    &:hover {
      border-color: var(--el-color-primary-light-7);
      box-shadow: 0 2px 12px 0 rgb(0 0 0 / 5%);
      transform: translateX(4px);
    }

    .el-checkbox {
      width: 100%;
      margin-right: 0;

      :deep(.el-checkbox__label) {
        width: 100%;
      }
    }

    .route-info {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;

      .route-title {
        flex: 1;
        margin-right: 8px;
        font-size: 14px;
        color: var(--el-text-color-regular);
      }
    }

    .info-icon {
      margin-left: 8px;
      font-size: 16px;
      color: var(--el-text-color-secondary);
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        color: var(--el-color-primary);
        transform: scale(1.1);
      }
    }
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
    padding: 16px 0;
    margin-top: 20px;
  }
}

.permission-tabs {
  :deep(.el-tabs__content) {
    padding: 20px 0;
  }
}

.permission-table-container {
  height: calc(94vh - 270px);
  overflow: hidden;
}

.permission-matrix {
  height: calc(90vh - 400px);
  padding: 16px;
  overflow-x: auto;
  background-color: var(--el-bg-color);
  border-radius: 8px;

  .permission-row {
    display: grid;
    grid-template-columns: repeat(3, minmax(300px, 1fr));
    gap: 16px;
    min-width: 900px;
    margin-bottom: 16px;
  }

  .permission-card {
    position: relative;
    padding: 16px;
    background: var(--el-bg-color-overlay);
    border: 1px solid var(--el-border-color-light);
    border-radius: 8px;
    transition: all 0.3s ease;

    &:hover {
      border-color: var(--el-color-primary-light-7);
      box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
      transform: translateY(-2px);
    }

    .el-checkbox {
      display: flex;
      width: 100%;
      margin-right: 0;

      :deep(.el-checkbox__label) {
        flex: 1;
        width: 100%;
      }
    }
  }

  .permission-card-content {
    width: 100%;
  }

  .permission-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 8px;
    font-size: 14px;
    font-weight: 500;
    color: var(--el-text-color-primary);
    word-break: break-all;

    .info-icon {
      flex-shrink: 0;
      margin-left: 8px;
      font-size: 16px;
      color: var(--el-text-color-secondary);
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        color: var(--el-color-primary);
        transform: scale(1.1);
      }
    }
  }

  .permission-info {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-top: 8px;
    font-size: 12px;
    color: var(--el-text-color-secondary);

    .permission-id,
    .permission-pid {
      padding: 2px 6px;
      background-color: var(--el-fill-color-light);
      border-radius: 4px;
    }
  }
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding: 16px;
  margin-top: 16px;
  background-color: var(--el-bg-color);
  border-radius: 8px;
}

.mb-4 {
  margin-bottom: 16px;
}

.mr-2 {
  margin-right: 8px;
}

.data-range-content {
  .form-item {
    position: relative;
    z-index: 1;
    margin-bottom: 16px;
  }

  .label {
    margin-bottom: 8px;
    font-weight: bold;
  }

  :deep(.el-table) {
    max-height: 500px;
    margin-top: 20px;
    overflow-y: auto;
  }

  :deep(.el-select) {
    width: 100%;
  }
}

.drawer-content {
  padding: 20px;

  .field-info {
    p {
      margin: 8px 0;
      color: var(--el-text-color-regular);

      strong {
        color: var(--el-text-color-primary);
      }
    }
  }

  .drawer-footer {
    position: absolute;
    right: 20px;
    bottom: 20px;
    display: flex;
    justify-content: flex-end;
    width: calc(100% - 40px);
    padding-top: 20px;
    border-top: 1px solid var(--el-border-color-light);

    .el-button + .el-button {
      margin-left: 12px;
    }
  }
}

.tags-container {
  padding: 16px;
  background-color: var(--el-fill-color-blank);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 4px;

  .el-tag {
    margin-right: 8px;
    margin-bottom: 8px;
  }

  .button-new-tag {
    height: 24px;
    padding-top: 0;
    padding-bottom: 0;
    margin-bottom: 8px;
    line-height: 22px;
  }

  .input-new-tag {
    width: 90px;
    margin-right: 8px;
    vertical-align: bottom;
  }
}

.ml-1 {
  margin-left: 4px;
}

.w-20 {
  width: 80px;
}

.vertical-tree-container {
  height: calc(90vh - 280px);
  padding: 20px;
  overflow-y: auto;
  background-color: var(--el-bg-color);
  border-radius: 8px;

  :deep(.el-tree) {
    background-color: transparent;

    .el-tree-node__content {
      height: 36px;

      &:hover {
        background-color: var(--el-fill-color-light);
      }
    }
  }

  .custom-tree-node {
    display: flex;
    align-items: center;
    width: 100%;

    span {
      flex: 1;
      margin-right: 8px;
    }

    .info-icon {
      font-size: 14px;
      color: var(--el-text-color-secondary);
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        color: var(--el-color-primary);
        transform: scale(1.1);
      }
    }
  }
}
</style>
